package com.htfyun.factorytest.factorytestui;

import android.app.admin.DevicePolicyManager;
import android.content.Intent;
import android.hardware.fingerprint.Fingerprint;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.Handler;
import android.os.Message;
import android.os.UserHandle;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.biometric.BiometricPrompt;
import androidx.core.content.ContextCompat;

import com.android.internal.widget.LockPatternUtils;
import com.htfyun.factorytest.ViewDialogFragment;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executor;

import com.htfyun.factorytest.R;

import com.htfyun.factorytest.utils.DebugLog;
import com.htfyun.factorytest.utils.executor.AppExecutors;

/**
 * <pre>
 *     author : Administrator
 *     e-mail : tancheng@htfyun.com
 *     time   : 2020/09/10
 *     desc   :
 *     version: 1.0
 * </pre>
 */
public class FactoryFingerprintActivity extends FactoryBaseActivity implements ViewDialogFragment.Callback {
    @Override
    public void onClick() {

    }

    @Override
    int getLayoutId() {
        return 0;
    }

    @Override
    void onInitView(@Nullable Bundle savedInstanceState) {

    }

    @Override
    void onHandleMessage(Handler handler, Message msg) {

    }
//    private static final int REQUESTCODE_FINGERPRINT_ENROLLMENT = 0x100;
//    private int TEST_FINGER_ID = 9;
//    private boolean mIsNeedClearPassword;
//    private FingerprintManager mFingerprintManager;
//    private int mTouchCounts = 0;
//    private int mCurrentUserId;
//    private TextView mEnrolCountTV;
//    private ProgressBar mEnrolProgressBar;
//    private TextView mEnrolQualityTV;
//    CancellationSignal enrollCancelSig = new CancellationSignal();
//    String LOCK_PATTERN_UTILS = "com.android.internal.widget.LockPatternUtils";
//    private int mRequestedQuality = DevicePolicyManager.PASSWORD_QUALITY_NUMERIC;// 数字密码
//    private static final String LOCK_SCREEN_PASSWORD = "000000";
//    private LockPatternUtils utils;
//
//    private Executor executor;
//    private BiometricPrompt biometricPrompt;
//    private BiometricPrompt.PromptInfo promptInfo;
//
//    private ViewDialogFragment dialogOnEnrolled;
//
//    @Override
//    int getLayoutId() {
//        return R.layout.activity_factory_fingerprint;
//    }
//
//    @Override
//    void onInitView(@Nullable Bundle savedInstanceState) {
//        mEnrolCountTV = findViewById(R.id.fod_enrolCountTV);
//        mEnrolQualityTV = findViewById(R.id.fod_enrolQualityTV);
//        mEnrolProgressBar = findViewById(R.id.fod_enrolProgressBar);
//        mEnrolProgressBar.setScaleY(3f);
//
//        mIsNeedClearPassword = true;
//        mCurrentUserId = 0;
//        utils = new LockPatternUtils(this);
//
//        mFingerprintManager = getSystemService(FingerprintManager.class);
//        if (!mFingerprintManager.isHardwareDetected()) {
//            DebugLog.e("Fail for NO FP!");
//            finishWithFail();
//        }
//
//        executor = ContextCompat.getMainExecutor(this);
//        biometricPrompt = new BiometricPrompt(this, executor, new BiometricPrompt.AuthenticationCallback() {
//            @Override
//            public void onAuthenticationSucceeded(@NonNull BiometricPrompt.AuthenticationResult result) {
//                super.onAuthenticationSucceeded(result);
//                Toast.makeText(getApplicationContext(),
//                        "验证成功", Toast.LENGTH_SHORT).show();
//                mIsNeedClearPassword = true;
//                finishWithOK();
//            }
//        });
//
//        promptInfo = new BiometricPrompt.PromptInfo.Builder()
//                .setTitle("验证指纹")
//                .setSubtitle("请使用录入指纹的手指触摸指纹模块")
//                .setNegativeButtonText("取消")
//                .build();
//
//    }
//
//    @Override
//    protected void onResume() {
//        if (utils.isLockPasswordEnabled(mCurrentUserId) || utils.isLockPatternEnabled(mCurrentUserId)) {
///*            DebugLog.e(getString(R.string.fp_can_not_enroll));
//            Toast.makeText(this, getString(R.string.fp_can_not_enroll), Toast.LENGTH_LONG).show();
//            mIsNeedClearPassword = false;
//            finishWithFail();*/
//            if (mIsNeedClearPassword) {
//                removeFinger(TEST_FINGER_ID);
//                removeLockPassword();
//            }
//        }
//        super.onResume();
//
//        if (mIsNeedClearPassword) {
//            setLockPassword();
//            if (!mFingerprintManager.hasEnrolledFingerprints()) {
//                startEnrol(TEST_FINGER_ID);
//            } else {
//                startVerify();
//            }
//        }
//
//    }
//
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (resultCode == REQUESTCODE_FINGERPRINT_ENROLLMENT) {
//            biometricPrompt.authenticate(promptInfo);
//        }
//    }
//
//    @Override
//    void onHandleMessage(Handler handler, Message msg) {
//
//    }
//
//    @Override
//    protected void onPause() {
//        DebugLog.i("onPause()");
//        if (mIsNeedClearPassword) {
//            removeFinger(TEST_FINGER_ID);
//            removeLockPassword();
//        }
//        super.onPause();
//    }
//
//    @Override
//    protected void onDestroy() {
//        DebugLog.i("onDestroy()");
//        if (mIsNeedClearPassword) {
//            removeFinger(TEST_FINGER_ID);
//            removeLockPassword();
//        }
//        super.onDestroy();
//    }
//
//    private void setLockPassword() {
//        DebugLog.i("Before test, set lock password as " + LOCK_SCREEN_PASSWORD);
//
//        try {
////            ReflectUtils.reflect(LOCK_PATTERN_UTILS).newInstance(mContext).method("setCredentialRequiredToDecrypt", false).get();
////            ReflectUtils.reflect(LOCK_PATTERN_UTILS).newInstance(mContext).method("saveLockPassword", LOCK_SCREEN_PASSWORD, null, mRequestedQuality, 0).get();
//            utils.setCredentialRequiredToDecrypt(false);
//            utils.saveLockPassword(LOCK_SCREEN_PASSWORD, null, mRequestedQuality, 0);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//    }
//
//    private void removeFinger(int removeFingerID) {
//        DebugLog.i("removeFinger( " + removeFingerID + " )");
//        List<Fingerprint> prints = mFingerprintManager.getEnrolledFingerprints();
//        if (prints == null || prints.size() == 0) {
//            DebugLog.i("removeFinger( ) fingerId no exit");
//            return;
//        }
//        MyRemovalCallback removalCallback = new MyRemovalCallback();
//        for (int i = 0; i < prints.size(); i++) {
//            Fingerprint fp = prints.get(i);
//            DebugLog.i("removeFinger()-mFingerIds[" + i + "]=" + fp.getFingerId());
//            mFingerprintManager.remove(fp, 0, removalCallback);
//            String sb = "removeFinger: " +
//                    fp.getFingerId();
//            DebugLog.i(sb);
//        }
//        Toast.makeText(this, "test finger remove", Toast.LENGTH_LONG).show();
//    }
//
//    private void removeLockPassword() {
//        DebugLog.i("After test, remove lock password");
////        ReflectUtils.reflect(LOCK_PATTERN_UTILS).newInstance(mContext).method("clearLock", LOCK_SCREEN_PASSWORD, 0).get();
//        try {
//            if (utils.isLockPasswordEnabled(getUserId()))
//                utils.clearLock(LOCK_SCREEN_PASSWORD, 0);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//    }
//
//    private void startEnrol(final int enrolFingerID) {
//        AppExecutors.runOnIoThread(() -> {
//            DebugLog.i("startEnrol(" + enrolFingerID + ")");
//            MyEnrollmentCallback callback = new MyEnrollmentCallback();
//            long token = mFingerprintManager.preEnroll();
//            DebugLog.i("FingerprintManager.preEnroll() return token: " + token);
//            DebugLog.i("Process.myUid(): " + UserHandle.myUserId());
//            if (token == 0) {
////                    updatePassFailButton(false);
//                return;
//            }
//            try {
//                DebugLog.e("****** utils " + utils);
//                byte[] bToken = utils.verifyPassword(LOCK_SCREEN_PASSWORD, token, UserHandle.myUserId());
//                DebugLog.i("LockPatternUtils.verifyPassword() return token: " + Arrays.toString(bToken));
//                if (bToken == null) {
//                    DebugLog.e("Please check your lockScreen passwork is " + LOCK_SCREEN_PASSWORD);
////                        updatePassFailButton(false);
//                } else {
//                    mFingerprintManager.enroll(bToken, enrollCancelSig, 0, 0, callback);
//                    mTouchCounts = 0;
//                    DebugLog.i("startEnrol(" + enrolFingerID + ") finished");
//                }
//            } catch (Exception e) {
//                DebugLog.e(e.getMessage());
//                e.printStackTrace();
//            }
//        });
//
//    }
//
//    private void finishEnrol() {
//        DebugLog.i("finishEnrol()");
//        mFingerprintManager.postEnroll();
//        mTouchCounts = 0;
//        mEnrolCountTV.setText("");
//    }
//
//    public void onEnrolled(int fingerId) {
//        DebugLog.i("onEnrolled( " + fingerId + " )");
//        finishEnrol();
//        TEST_FINGER_ID = fingerId;
//        mEnrolCountTV.setText("");
//        showDialogOnEnrolled();
//    }
//
//    public void onProgress(int enrolPercent) {
//        DebugLog.i("Enrollment onProgress: " + enrolPercent + "%");
//        mTouchCounts++;
//        mEnrolProgressBar.setProgress(enrolPercent);
//        String sb = mTouchCounts +
//                (mTouchCounts > 1 ? " touches  " : " touch  ") +
//                enrolPercent +
//                "%";
//        mEnrolCountTV.setText(sb);
////        mEnrolQualityTV.setText(showMsg);
//        if (100 == enrolPercent) {
//            onEnrolled(TEST_FINGER_ID);
//        }
//    }
//
//    private void startVerify() {
//        biometricPrompt.authenticate(promptInfo);
//
//    }
//
//    private class MyEnrollmentCallback extends FingerprintManager.EnrollmentCallback {
//
//        MyEnrollmentCallback() {
//        }
//
//        public void onEnrollmentError(int errMsgId, CharSequence errString) {
//            DebugLog.i("MyEnrollmentCallback.onEnrollmentError() errMsgId: " + errMsgId + ", errString: " + errString);
//            mEnrolQualityTV.setText(errString);
//
//        }
//
//        public void onEnrollmentHelp(int helpMsgId, CharSequence helpString) {
//            DebugLog.i("MyEnrollmentCallback.onEnrollmentHelp() helpMsgId: " + helpMsgId + ", helpString: " + helpString);
//            mEnrolQualityTV.setText(helpString);
//
//        }
//
//        public void onEnrollmentProgress(int remaining) {
//            DebugLog.i("MyEnrollmentCallback.onEnrollmentProgress() remaining: " + remaining);
//            mEnrolQualityTV.setText("");
//            onProgress((20 - remaining) * 5);
//
//        }
//
//    }
//    public class MyRemovalCallback extends FingerprintManager.RemovalCallback {
//
//        MyRemovalCallback() {
//        }
//        public void onRemovalError(Fingerprint fp, int errMsgId, CharSequence errString) {
//            DebugLog.i("MyRemovalCallback.onRemovalError() fingerprint: " + fp + ", errMsgId: " + errMsgId + ", errString: " + errString);
//        }
//
//        public void onRemovalSucceeded(Fingerprint fp, int remaining) {
//            DebugLog.i("MyRemovalCallback.onRemovalSucceeded() fingerprint: " + fp);
//        }
//
//    }
//    private void dismissDialogOnEnrolled() {
//
//        if (dialogOnEnrolled != null) {
//            dialogOnEnrolled.dismiss();
//            dialogOnEnrolled = null;
//        }
//    }
//
//    private void showDialogOnEnrolled() {
//
//        if (dialogOnEnrolled == null) {
//            final String title = getString(R.string.fingerprint_event);
//            final String msg = getString(R.string.fingerprint_onEnrolled);
//            dialogOnEnrolled = ViewDialogFragment.newInstance(title, msg, false);
//        }
//
//        if (!dialogOnEnrolled.isShowing()) {
//            dialogOnEnrolled.show(getFragmentManager(), this, null);
//        }
//    }
//
//    @Override
//    public void onClick() {
//        mEnrolQualityTV.setText(getString(R.string.fingerprint_onEnrolled));
//        startVerify();
//    }
//
///*    private class MyAuthenticationCallback extends FingerprintManager.AuthenticationCallback {
//        MyAuthenticationCallback() {
//        }
//
//        public void onAuthenticationError(int errorCode, CharSequence errString) {
//            DebugLog.i("MyAuthenticationCallback.onAuthenticationError() errorCode: " + errorCode + ", errString: " + errString);
//            showCommonBars(true);
//            setPassButtonEnable(false);
//            setFailButtonEnable(true);
//        }
//
//        public void onAuthenticationHelp(int helpCode, CharSequence helpString) {
//            DebugLog.i("MyAuthenticationCallback.onAuthenticationHelp() helpCode: " + helpCode + ", helpString: " + helpString);
//        }
//
//        public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
//            DebugLog.i("MyAuthenticationCallback.onAuthenticationSucceeded() result: " + result);
//            finishWithOK();
//            onIdentified(TEST_FINGER_ID);
//            startVerify();
//            setPassButtonEnable(true);
//            pass();
//            setFailButtonEnable(true);
//        }
//
//        public void onAuthenticationFailed() {
//            DebugLog.i("MyAuthenticationCallback.onAuthenticationFailed()");
//            onNoMatch(mVerifyFailCounts);
//        }
//
//        public void onAuthenticationAcquired(int acquireInfo) {
//            DebugLog.i("MyAuthenticationCallback.onAuthenticationAcquired() acquireInfo: " + acquireInfo);
//        }
//    }*/

}
